<template>
  <div class="login-container">
    <el-form ref="form" :model="loginForm" label-width="80px" class="login-form">
      <h2>管理员登录</h2>

      <el-form-item label="用户名">
        <el-input v-model="loginForm.username"></el-input>
      </el-form-item>

      <el-form-item label="密码">
        <el-input v-model="loginForm.password" show-password></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">登录</el-button>
        <el-button @click="fillDemoAccount" type="text">显示演示账号</el-button>
      </el-form-item>

      <p style="color: #999; font-size: 13px;">提示：测试账号 admin / 密码 test</p>
      <p style="font-size: 13px;">
        还没有账号？
        <el-button @click="$router.push('/register')" type="text">立即注册</el-button>
      </p>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    onSubmit() {
      const { username, password } = this.loginForm

      // 尝试从 localStorage 获取注册用户
      const storedUser = localStorage.getItem(`user_${username}`)
      if (storedUser) {
        const user = JSON.parse(storedUser)
        if (user.password === password) {
          this.$message.success('登录成功')
          localStorage.setItem('isLoggedIn', 'true')
          this.$router.push('/')
        } else {
          this.$message.error('密码错误')
        }
      } else if (username === 'admin' && password === 'test') {
        this.$message.success('登录成功')
        localStorage.setItem('isLoggedIn', 'true')
        this.$router.push('/')
      } else {
        this.$message.error('用户名或密码错误')
      }
    },
    fillDemoAccount() {
      this.loginForm.username = 'admin'
      this.loginForm.password = 'test'
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-form {
  width: 400px;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}
</style>